// TestSortDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TestSort.h"
#include "TestSortDlg.h"
#include <Shlwapi.h>
#include ".\testsortdlg.h"
#include "StdioFileEx.h"
#include <string>
using namespace std;

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#ifdef _UNICODE
    #define tstring wstring
#else
    #define tstring string
#endif

enum tagCompareType
{
    ct_tcscmp = 0,
    ct_tcsicmp,
    ct_StrCmp,
    ct_StrCmpI,
    ct_StrCmpC,
    ct_StrCmpIC,
    ct_StrCmpLogicalW,
    ct_StrCmpN,
    ct_lstrcmp,
    ct_lstrcmpi,
    ct_CStringCompare,
    ct_CStringCompareNoCase,
    ct_tstringcompare,
    ct_CompareString
};

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CTestSortDlg dialog



CTestSortDlg::CTestSortDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTestSortDlg::IDD, pParent)
    , m_CompareType(0)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CTestSortDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_LIST1, m_ListCtrl);
    DDX_Radio(pDX,IDC_RADIO_TCSCMP,m_CompareType);
}

BEGIN_MESSAGE_MAP(CTestSortDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
    ON_WM_SIZE()
    ON_BN_CLICKED(IDC_LOADFILE, OnBnClickedLoadFile)
    ON_NOTIFY(HDN_ITEMCLICK, 0, OnHdnItemclickList1)
    ON_BN_CLICKED(IDC_MAKEFOLDER, OnBnClickedMakeFolder)
    ON_BN_CLICKED(IDC_OPENFOLDER, OnBnClickedOpenfolder)
    ON_WM_DESTROY()
END_MESSAGE_MAP()


// CTestSortDlg message handlers

BOOL CTestSortDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

    

	// TODO: Add extra initialization here
	m_ListCtrl.InsertColumn(0,_T("NAME"),LVCFMT_LEFT,300);
    m_ListCtrl.SetExtendedStyle( LVS_EX_FULLROWSELECT );

    //m_ListCtrl.SetHeadings( _T("Name,300"));
    //m_ListCtrl.LoadColumnInfo();

#if (_WIN32_IE >= 0x0603)
    ::EnableWindow(::GetDlgItem(m_hWnd,IDC_RADIO_STRCMPC),TRUE);
    ::EnableWindow(::GetDlgItem(m_hWnd,IDC_RADIO_STRCMPIC),TRUE);
#endif
    DlgResize_Init(FALSE);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CTestSortDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CTestSortDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTestSortDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CTestSortDlg::OnSize(UINT nType, int cx, int cy)
{
    //__super::OnSize(nType, cx, cy);
    BOOL b;
    CMFCDialogResize<CTestSortDlg>::OnSize(WM_SIZE,(WPARAM)nType,(LPARAM)MAKELONG(cx,cy),b);
}

void CTestSortDlg::ClearMemory()
{
    for (int i = 0 ; i< m_ListCtrl.GetItemCount(); i++)
    {
        LPTSTR pszName = (LPTSTR) m_ListCtrl.GetItemData(i);
        delete []pszName;
        m_ListCtrl.SetItemData(i,NULL);
    }
}

void CTestSortDlg::OnBnClickedLoadFile()
{
    static TCHAR szFilter[] = _T("Text Files (*.txt)|*.txt|All Files (*.*)|*.*||");

#if 1
    CFileDialog dlg(TRUE,_T(".txt"),NULL,0,szFilter);
    if (dlg.DoModal())
    {
        ClearMemory();
        m_ListCtrl.DeleteAllItems();
        CString strInfo;
#ifdef _UNICODE
        CStdioFileEx2 file(dlg.GetPathName(),CFile::modeRead|CFile::typeText);
        while (file.ReadWideString(strInfo))
#else
        CStdioFileEx file(dlg.GetPathName(),CFile::modeRead|CFile::typeText);
        while (file.ReadString(strInfo))
#endif
        {
            strInfo.TrimRight(_T("\r\n"));
            int len = strInfo.GetLength() + 1;
            LPTSTR pszName = new TCHAR[len];
            ZeroMemory(pszName,sizeof(TCHAR) * len);
            _tcscpy(pszName,strInfo);
            INT Index = m_ListCtrl.InsertItem(m_ListCtrl.GetItemCount(),strInfo);
            m_ListCtrl.SetItemData(Index,(DWORD_PTR)pszName);

        }
        file.Close();
    }
#endif
}

void CTestSortDlg::OnHdnItemclickList1(NMHDR *pNMHDR, LRESULT *pResult)
{
    UpdateData(TRUE);
    
    CString strCompareType = _T("");

    //Used for debug
    switch(m_CompareType)
    {
    case ct_tcscmp: 
        strCompareType = _T("_tcscmp");
        break;
    case ct_tcsicmp:
        strCompareType = _T("_tcsicmp");
        break;
    case ct_StrCmp:
        strCompareType = _T("StrCmp");
        break;
    case ct_StrCmpI:
        strCompareType = _T("StrCmpI");
        break;
#if (_WIN32_IE >= 0x0603)
    case ct_StrCmpC:
        strCompareType = _T("StrCmpC");
        break;
    case ct_StrCmpIC:
        strCompareType = _T("StrCmpIC");
        break;
#endif
    case ct_StrCmpLogicalW:
        strCompareType = _T("StrCmpLogicalW");
        break;
    case ct_StrCmpN:
        strCompareType = _T("StrCmpN");
        break;
    case ct_lstrcmp:
        strCompareType = _T("lstrcmp");
        break;
    case ct_lstrcmpi:
        strCompareType = _T("lstrcmpi");
        break;
    case ct_CStringCompare:
        strCompareType = _T("CString::Compare");
        break;
    case ct_CStringCompareNoCase:
        strCompareType = _T("CString::CompareNoCase");
        break;
    case ct_tstringcompare:
        strCompareType = _T("tstring::compare");
        break;
    case ct_CompareString:
        strCompareType = _T("CompareString");
        break;
    default:
        _ASSERT(FALSE);
        break;
    }
    SetWindowText(strCompareType);


    LPNMHEADER phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);
    // TODO: Add your control notification handler code here
    NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
    const int iColumn = pNMListView->iSubItem;

    // if it's a second click on the same column then reverse the sort order,
    // otherwise sort the new column in ascending order.
    Sort( iColumn, iColumn == m_iSortColumn ? !m_bSortAscending : TRUE );
    *pResult = 0;
}

int CALLBACK CTestSortDlg::CompareFunction( LPARAM lParam1, LPARAM lParam2, LPARAM lParamData )
{
    CTestSortDlg* pThis = reinterpret_cast<CTestSortDlg*>( lParamData );

    LPTSTR str1 = (LPTSTR)lParam1;// pThis->m_ListCtrl.GetItemText(index1,0);
    LPTSTR str2 = (LPTSTR)lParam2;//pThis->m_ListCtrl.GetItemText(index2,0);

    int nResult = 0;
    switch(pThis->m_CompareType)
    {
    case ct_tcscmp:
        nResult = _tcscmp(str1,str2);
    	break;
    case ct_tcsicmp:
        nResult = _tcsicmp(str1,str2);
        break;
    case ct_StrCmp:
        nResult = StrCmp(str1,str2);
        break;
    case ct_StrCmpI:
        nResult = StrCmpI(str1,str2);
        break;
#if (_WIN32_IE >= 0x0603)
    case ct_StrCmpC:
        nResult = StrCmpC(str1,str2);
        break;
    case ct_StrCmpIC:
        nResult = StrCmpIC(str1,str2);
        break;
#endif
    case ct_StrCmpLogicalW:
        {
            USES_CONVERSION;
            nResult = StrCmpLogicalW(T2W(str1),T2W(str2));
        }
        break;
    case ct_StrCmpN:
        nResult = StrCmpN(str1,str2,max(lstrlen(str1),lstrlen(str2))); //can't be min
        break;
    case ct_lstrcmp:
        nResult = lstrcmp(str1,str2);
        break;
    case ct_lstrcmpi:
        nResult = lstrcmpi(str1,str2);
        break;
    case ct_CStringCompare:
        {
            CString cStr1(str1);
            nResult = cStr1.Compare(str2);
        }
        break;
    case ct_CStringCompareNoCase:
        {
            CString cStr1(str1);
            nResult = cStr1.CompareNoCase(str2);
        }
        break;
    case ct_tstringcompare:
        {
            tstring tstr1 = str1;
            nResult = tstr1.compare(str2);
        }
        break;
    case ct_CompareString:
        {
            nResult = CompareString(LOCALE_USER_DEFAULT,
                NORM_IGNORECASE/*NORM_IGNORENONSPACE,NORM_IGNORESYMBOLS,NORM_IGNORESYMBOLS,NORM_IGNOREWIDTH*/
                ,str1,-1,str2,-1);
        }
        break;
    default:
        _ASSERT(FALSE);
        break;
    }
    if (pThis->m_bSortAscending)
    {
        return -nResult;
    }
    else
    {
        return nResult;
    }
}

void CTestSortDlg::Sort(int iColumn, BOOL bAscending )
{
    m_iSortColumn = iColumn;
    m_bSortAscending = bAscending;

    VERIFY( m_ListCtrl.SortItems( CompareFunction, reinterpret_cast<DWORD>( this ) ) );
}

void CTestSortDlg::OnBnClickedMakeFolder()
{
    int count = m_ListCtrl.GetItemCount();
    TCHAR bufPath[MAX_PATH] = {0};
    GetModuleFileName(NULL,bufPath,MAX_PATH);
    
    CString strPath = bufPath;
    int nPathLen = strPath.ReverseFind(_T('\\'));
    strPath.Delete(nPathLen + 1,strPath.GetLength() - nPathLen);

    CString strName = _T("");
    for (int i = 0; i< count ; i ++)
    {
        strName = m_ListCtrl.GetItemText(i,0);
        strName = strPath + strName;
        BOOL bOK =CreateDirectory(strName,NULL);
        if (!bOK)
        {
            TRACE(_T("CreateDirectory %s Failed:%d\n"),strName,GetLastError());
        }
    }
}

void CTestSortDlg::OnBnClickedOpenfolder()
{
    int count = m_ListCtrl.GetItemCount();
    TCHAR bufPath[MAX_PATH] = {0};
    GetModuleFileName(NULL,bufPath,MAX_PATH);

    CString strPath = bufPath;
    int nPathLen = strPath.ReverseFind(_T('\\'));
    strPath.Delete(nPathLen + 1,strPath.GetLength() - nPathLen);

    ShellExecute(m_hWnd,_T("open"),strPath,NULL,NULL,SW_SHOWNORMAL);
}

void CTestSortDlg::OnDestroy()
{
    ClearMemory();
    __super::OnDestroy();

    // TODO: Add your message handler code here
}
